package com.ruoyi.doc.service.impl;

import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.ofbiz.OfbizBaseService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.doc.domain.Company;
import com.ruoyi.doc.service.ICompanyService;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.constant.ConstKit;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.service.ServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CompanyServiceImpl extends OfbizBaseService implements ICompanyService {

    private static final Logger log = LoggerFactory.getLogger(CompanyServiceImpl.class);

    @Autowired
    private SysDeptMapper deptMapper;

    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        // 后期视情况决定是否将目录挂接到机构树下
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDept dept : depts) {
            tempList.add(dept.getDeptId());
        }
        for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext(); ) {
            SysDept dept = (SysDept) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    @Override
    public Map<String, Object> selectCompanyList(Company company, Integer pageNum, Integer pageSize, String orderBy) {
        LocalDispatcher dispatcher = getDispatcher();
        Map<String, Object> returnMap = null;
        Map<String, Object> context = new HashMap<>();
        context.put("company", company);
        context.put("pageNum", pageNum);
        context.put("pageSize", pageSize);
        context.put("orderBy", orderBy);
        try {
            returnMap = dispatcher.runSync("selectCompanyList", context);
        } catch (GenericServiceException e) {
            log.error("selectCompanyList Error", e);
            return ServiceUtil.returnError(e.getMessage());
        }
        return returnMap;
    }

    @Override
    public List<SysDept> selectLazyDept(Long parentNodeId) {
        LocalDispatcher dispatcher = getDispatcher();
        List<SysDept> sysDepts = deptMapper.selectChildrenDeptById(parentNodeId);
        List<SysDept> childParents = new ArrayList<>();
        if (UtilValidate.isNotEmpty(sysDepts)) {
            for (SysDept dept : sysDepts) {
                if (parentNodeId.equals(dept.getParentId())) {
                    childParents.add(dept);
                }
            }
        }
        // 查询当前节点下的文件夹
        try {
            Map<String, Object> returnMap = dispatcher.runSync("selectPartyContent", UtilMisc.toMap("parentNodeId", String.valueOf(parentNodeId), "partyContentTypeId", ConstKit.CONTENT_TYPE_FOLDER));
            if (!ServiceUtil.isSuccess(returnMap)) {
                return childParents;
            }
            List<GenericValue> contentList = UtilGenerics.cast(returnMap.get("contentList"));
            if (UtilValidate.isNotEmpty(contentList)) {
                for (GenericValue contentValue : contentList) {
                    SysDept dept = new SysDept();
                    dept.setDeptId(UtilMisc.toLong(contentValue.get("contentId")));
                    dept.setDeptName(contentValue.getString("contentName"));
                    childParents.add(dept);
                }
            }
        } catch (GenericServiceException e) {
            log.error("selectPartyContent Error", e);
            return Collections.emptyList();
        }
        return childParents;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }

}
